package com.baibei.ebec.quotation;

import android.util.Log;
import android.util.SparseArray;

import com.baibei.ebec.quotation.converter.MarkeStatusConverter;
import com.baibei.ebec.quotation.converter.QuotationInfoConverter;
import com.baibei.ebec.quotation.converter.TradeResponseConverter;
import com.baibei.model.QuotationInfo;
import com.baibei.quotation.BaibeiQuotationManager;
import com.blankj.utilcode.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 行情管理器
 * Created by ChenRui on 2017/5/8 0008 14:21.
 */
public final class QuotationManager extends BaibeiQuotationManager {

    private static QuotationManager manager;

    /**
     * 获取行情管理器的实例
     */
    public static QuotationManager getInstance() {
        if (manager == null) {
            synchronized (QuotationManager.class) {
                if (manager == null) {
                    manager = new QuotationManager();
                }
            }
        }
        return manager;
    }

    private QuotationManager() {
        super(BuildConfig.WEB_SOCKET_URL);
        // 行情解析
        addDispatchMessage(new QuotationInfoConverter());
        addDispatchMessage(new TradeResponseConverter());
        addDispatchMessage(new MarkeStatusConverter());
    }

    @Override
    public String getCacheFileName() {
        return ".ebec_quotation_cache";
    }

    @Override
    public void destroy() {
        super.destroy();
        QuotationInfoCache.clear();
    }

    /**
     * 发送文本信息
     *
     * @param type
     * @param data
     */
    public void sendTextMessage(String type, String data) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("type", type);
            obj.put("data", data);
            String text = obj.toString();
            send(text);
            LogUtils.i("QuotationWebSocket", "发送消息：" + text);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定用户信息
     *
     * @param accessToken token
     */
    public void bindUserInfo(String accessToken) {
        sendTextMessage("BINDING_USER", accessToken);
    }

    /**
     * 绑定交易所
     *
     * @param exchange exchange
     */
    public void bindExchange(String exchange) {
        sendTextMessage("BINDING_EXCHANGE", exchange);
    }

    /**
     * 从缓存中加载数据
     */
    public void flushCache() {
        SparseArray<QuotationInfo> cache = getCache();
        if (cache != null) {
            EventBus.getDefault().post(cache);
        }
        super.flushCache();
    }

    /**
     * 获取缓存的行情
     *
     * @return
     */
    public SparseArray<QuotationInfo> getCache() {
        return QuotationInfoCache.get();
    }


}
